package com.azt.back.action.user;

import com.alibaba.fastjson.JSONArray;
import com.azt.api.pojo.CenCollection;
import com.azt.api.pojo.Company;
import com.azt.api.pojo.Member;
import com.azt.api.pojo.MemberDetail;
import com.azt.api.pojo.MemberDetailVO;
import com.azt.api.service.CompanyService;
import com.azt.api.service.MemberService;
import com.azt.api.service.ProductService;
import com.azt.back.action.BaseAction;
import com.azt.back.util.ContextUtils;
import com.azt.back.util.Globals;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.RequestUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/member")
public class MemberAction extends BaseAction {

    @Autowired
    private MemberService memberService;

    @Autowired
    private CompanyService companyservice;

    @Autowired
    private ProductService productService;


    @RequestMapping("/member_list.do")
    public String selectMemberList(Model model, HttpServletRequest request, Integer pageNo) {
        Map<String, String> searchMap = RequestUtils.getSearchMap(request);
        Pagination pagination = memberService.selectMemberList(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE, searchMap);
        model.addAttribute("pagination", pagination);
        RequestUtils.MapToModelMap(searchMap, request);
        return "member/member_list";
    }

    @RequestMapping("/member_add.do")
    public String addMember(Model model) {
        return "member/member_add";
    }

    @ResponseBody
    @RequestMapping("/providerCompany.do")
    public AjaxJson selectProviderCompany(Integer pageNo, HttpServletRequest request) {
        AjaxJson aj = new AjaxJson();
        try {
            Map<String, String> searchMap = RequestUtils.getSearchMap(request);
            searchMap.put("so_cusrole", "2");
            Pagination pagination = companyservice.getCompanyPage(pageNo == null ? 1 : pageNo, 6, searchMap);
            Map<String, Object> sources = new HashMap<>();
            sources.put("companyList", pagination.getList());
            sources.put("pageNo", pagination.getPageNo());
            sources.put("totalPage", pagination.getTotalPage());
            sources.put("so_customerinfo", searchMap.get("so_customerinfo"));
            aj.setAttributes(sources);
        } catch (Exception e) {
            e.printStackTrace();
            aj = AjaxJson.error("请求失败");
        }
        return aj;
    }

    @RequestMapping("/savemember.do")
    public String dosaveMember(Member member) {
        try {
            member.setState(1);
            member.setRemoved(0);
            memberService.saveMember(member);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/member/member_list.do";
    }

    @RequestMapping("/member_backpoint.do")
    public String backPoint(Integer mid, Model model) {
        Member member = memberService.selectMemberByid(mid);
        List<CenCollection> collectList=memberService.findCollectionByMember(mid);
        boolean canEdit = true;
        if(CollectionUtil.isNotEmpty(collectList)) {
            canEdit = false;
        }
        model.addAttribute("canEdit", canEdit);
        model.addAttribute("member", member);
        return "member/member_backpoint";
    }

    @ResponseBody
    @RequestMapping("/getBackPoint.do")
    public AjaxJson getBackPoint(Integer mid, Model model) {
        List<MemberDetail> mdlist = memberService.selectMemberDetailsBymid(mid);

        model.addAttribute("memberDetails", mdlist);
        return AjaxJson.success().setObj(mdlist);
    }

    @RequestMapping("/saveBackPoint.do")
    @ResponseBody
    public AjaxJson saveBackPoint(@RequestBody MemberDetailVO memberdetailarr) {
        AjaxJson aj = new AjaxJson();
        try {
            memberService.addMemberDetailList(memberdetailarr.getMemberDetails());
        } catch (Exception e) {
            e.printStackTrace();
            aj = AjaxJson.error("请求失败");
        }
        return aj;
    }

    @RequestMapping("/selectMemberDet.do")
    @ResponseBody
    public AjaxJson selectMemberDet(Integer mid) {
        AjaxJson aj = new AjaxJson();
        try {
            Map<String, Object> sources = new HashMap<>();
            List<MemberDetail> mdlist = memberService.selectMemberDetailsBymid(mid);
            sources.put("mdlist", mdlist);
            aj.setAttributes(sources);
        } catch (Exception e) {
            e.printStackTrace();
            aj = AjaxJson.error("系统出错");
        }
        return aj;
    }

    @RequestMapping("/validateSameMem.do")
    @ResponseBody
    public AjaxJson validateSameMem(String startdate,String mid) {
        AjaxJson aj = new AjaxJson();
        try {
            Member member = memberService.selectMemberByCompanyId(startdate,mid);
            if (member != null) {
                aj = AjaxJson.error("该供应商已存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            aj = AjaxJson.error("选择失败，数据无法验证");
        }
        return aj;
    }

    @RequestMapping("/price_edit.do")
    public String loadEditPrice(Model model) {
        Integer companyId = getParaToInt("companyId");
        Company company = companyservice.getCompanyById(companyId);
        model.addAttribute("company", company);
        return "member/price_edit";
    }

    @ResponseBody
    @RequestMapping("/searchMemberProduct.do")
    public AjaxJson searchMemberProduct() {
        Integer companyId = getParaToInt("companyId");
        String productName = getParaTrim("productName");
        Integer pageNo = getParaToInt("pageNo", 1);
        Integer pageSize = getParaToInt("pageSize", Globals.PAGE_SIZE);

        if (companyId != null) {
            Map param = new HashMap();
            param.put("companyId", companyId);
            param.put("productName", productName);
            Page page = PageHelper.startPage(pageNo, pageSize);
            memberService.searchMemberProduct(param);
            return AjaxJson.success().setObj(new PageInfo(page));
        }
        return AjaxJson.error("操作失败");
    }

    @RequestMapping("/cenMemberList.do")
	public String selectCenCollection(Model model,HttpServletRequest request,Integer pageNo){
		Map<String, String> searchMap = RequestUtils.getSearchMap(request);
		Pagination pagination = memberService.selectCenCollectionList(pageNo == null ? 1 : pageNo,Globals.PAGE_SIZE, searchMap);
		model.addAttribute("pagination", pagination);
		RequestUtils.MapToModelMap(searchMap, request);
		return "member/member_backmoney";
	}

    /**
     * 设置商品价格
     * */
    @ResponseBody
    @RequestMapping("/updateProductPrice.do")
    public AjaxJson updateProductPrice() {
        List<Map> data = (List<Map>) JSONArray.parse(getPara("data"));
        for(Map m : data) {
            Integer skuId = Convert.toInt(m.get("skuId"));
            Double price = Convert.toDouble(m.get("price"));
            Double memberPrice = Convert.toDouble(m.get("memberPrice"));
            Double hotPrice = Convert.toDouble(m.get("hotPrice"));
            Double cenPrice = Convert.toDouble(m.get("cenPrice"));

            if(skuId != null) {
                productService.updateProductPrice(skuId, price, memberPrice, hotPrice, cenPrice);
            }
        }
        return AjaxJson.success();
    }
    
    
    @RequestMapping("/back_money_view.do")
    public ModelAndView showbackmoney(ModelAndView mv,Integer cenMemberId){
    	   List<CenCollection> collectList=memberService.findCollectionByMember(cenMemberId);
        if(CollectionUtil.isNotEmpty(collectList)) {
            Iterator<CenCollection> iterator =  collectList.iterator();
            while (iterator.hasNext()) {
                CenCollection collection = iterator.next();
                if(collection != null && collection.getState().intValue() == 1) {
                    iterator.remove();
                }
            }
        }

    	   mv.setViewName("member/back_money");
    	   mv.addObject("collections", collectList);
    	   return mv;
    }
    
    @RequestMapping("/shoukuan.do")
    @ResponseBody
    public AjaxJson shoukuan(@RequestBody Member member){
    	AjaxJson aj=new AjaxJson();
    	try {
    		if(member.getCollections()!=null && member.getCollections().size()>0){
    			for(CenCollection c:member.getCollections()){
    				c.setOperateid(ContextUtils.getAdmin().getId());
    			}
    		}
			memberService.updateCenCollection(null, member.getCollections());
		} catch (Exception e) {
			aj=AjaxJson.error("操作失败，系统异常");
			e.printStackTrace();
		}
    	return aj;
    }
    
    @RequestMapping("/collect_detail.do")
    public String cenDetail(Model model) {
        Integer memberId = getParaToInt("memberId");
        Integer state = getParaToInt("state");
        if(memberId != null) {
            model.addAttribute("collect", memberService.getMingXiCollection(memberId, state));
        }
    	return "member/collect_minxi";
    }
    
    @ResponseBody
    @RequestMapping("/member_xuyue.do")
    public AjaxJson memberXuyue(Member member){
    	AjaxJson aj=new AjaxJson();
		try {
			memberService.updateCenMember(member);
		} catch (Exception e) {
			aj=AjaxJson.error("操作失败");
			e.printStackTrace();
		}
    	return aj;
    }
}
